/**
 * 
 */
package z.tool.dao;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import z.tool.util.Page;
import z.tool.util.ZUtils;

/**
 * @author auzll@163.com
 */
public class QueryResult<T> {
    private int count;
    private List<T> results;
    private Map<String, Object> others;
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private static final QueryResult EMPTY_RESULT  = new QueryResult(0, Collections.emptyList()) {
        public void setOthers(Map others) {
        }
        public QueryResult add(String key, Object value) {
            return this;
        }
    };
    
    @SuppressWarnings({"unchecked"})
    public static <T>QueryResult<T> emptyResult() {
        return EMPTY_RESULT;
    }
    
    public QueryResult() {
    }
    
    public QueryResult(int count, List<T> results) {
        this.count = count;
        this.results = results;
    }

    public int getCount() {
        return count;
    }

    public List<T> getResults() {
        return results;
    }
    
    public Map<String, Object> getOthers() {
        return others;
    }

    public void setOthers(Map<String, Object> others) {
        this.others = others;
    }
    
    public QueryResult<T> add(String key, Object value) {
        if (null == this.others) {
            this.others = ZUtils.newHashMap();
        }
        this.others.put(key, value);
        return this;
    }

    public String toString() {
        // 调试用
        StringBuilder sb = new StringBuilder();
        sb.append("count:").append(count).append("\r\nresults:\r\n");
        if (null != results && results.size() > 0) {
            for (Object t : results) {
                sb.append(t.toString()).append("\r\n");
            }
            sb.delete(sb.length()-"\r\n".length(), sb.length());
        }
        return sb.toString();
    }
    
    public Page toPage(Page page) {
        if (null == page) {
            page = new Page();
        }
        page.setCount(getCount());
        page.setOthers(getOthers());
        page.setRecordList(getResults());
        return page;
    }
    
    public Page toPage() {
        return toPage(null);
    }
}
